package com.zyx.lock.utils;

import com.zyx.lock.common.LockConstants;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * <p>基于redis的可重入分布式锁实现</p>
 *
 * @author Yaxi.Zhang
 * @since 2022/9/10 10:20
 */
public class DistributedRedisLock implements Lock {

    private final String lockName;
    private final StringRedisTemplate redisTemplate;
    private final String uuid;
    private final ThreadPoolTaskScheduler threadPoolTaskScheduler;
    private final long DEFAULT_EXPIRE = 30;
    private ScheduledFuture<?> future;

    public DistributedRedisLock(StringRedisTemplate redisTemplate, String lockName,
                                String uuid, ThreadPoolTaskScheduler threadPoolTaskScheduler) {
        this.lockName = lockName;
        this.redisTemplate = redisTemplate;
        this.uuid = uuid;
        this.threadPoolTaskScheduler = threadPoolTaskScheduler;
    }

    @Override
    public void lock() {
        this.tryLock();
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        try {
            return this.tryLock(-1L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean tryLock(long time, @NotNull TimeUnit unit) throws InterruptedException {
        long expire = time == -1 ? unit.toSeconds(DEFAULT_EXPIRE) : time;
        String script = "if redis.call('exists', KEYS[1]) == 0 or redis.call('hexists', KEYS[1] ,ARGV[1]) == 1 " +
                "then " +
                "   redis.call('hincrby', KEYS[1], ARGV[1], 1)  " +
                "   redis.call('expire',KEYS[1], ARGV[2]) " +
                "   return 1 " +
                "else " +
                "   return 0 " +
                "end";
        while (Boolean.FALSE.equals(redisTemplate.execute(new DefaultRedisScript<>(
                script, Boolean.class), List.of(lockName), uuid, String.valueOf(unit.toSeconds(expire))))) {
            TimeUnit.MILLISECONDS.sleep(50);
        }
        //System.out.println("count:" + redisTemplate.opsForHash().get(LockConstants.STOCK_KEY, uuid));
        //加锁成功，返回之前，开启定时器自动续期
        this.renewExpire(expire, unit);
        return true;
    }

    /**
     * 自动续期
     */
    private void renewExpire(long expire, @NotNull TimeUnit unit) {
        String script = "if redis.call('hexists',KEYS[1], ARGV[1]) == 1 " +
                "then " +
                "   return redis.call('expire',KEYS[1], ARGV[2]) " +
                "else " +
                "   return 0 " +
                "end";
       future = threadPoolTaskScheduler.scheduleAtFixedRate(() -> {
                    if (Boolean.FALSE.equals(redisTemplate.execute(new DefaultRedisScript<>(
                            script, Boolean.class), List.of(lockName), uuid, String.valueOf(DEFAULT_EXPIRE)))) {
                        // renewExpire(expire, unit);
                        future.cancel(true);
                    }
                }
                , unit.toMillis(expire) / 3);
    }

    @Override
    public void unlock() {
        String script = "if redis.call('hexists',KEYS[1],ARGV[1]) == 0 " +
                "then " +
                "   return nil " +
                "elseif redis.call('hincrby',KEYS[1],ARGV[1],-1) == 0 " +
                "then " +
                "   return redis.call('del',KEYS[1]) " +
                "else " +
                "   return 0 " +
                "end";
        // Long.class nil->null
        Long flag = this.redisTemplate.execute(
                new DefaultRedisScript<>(script, Long.class), List.of(lockName), uuid);
        if (flag == null) {
            throw new IllegalMonitorStateException("this lock doesn't belong to you !");
        }

    }

    @NotNull
    @Override
    public Condition newCondition() {
        return null;
    }
}
